﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using SAP.WebServices;
using System.Collections;
using System.Globalization;
using System.Net;

namespace SAP
{
    public partial class ItemMasterData : System.Web.UI.Page
    {
        private GeneralFunctions GF = new GeneralFunctions(HttpContext.Current.User.Identity.Name);
        public static DataTable dtHeader;
        private string TblHeaderName = "OITM";
        private string DocType = "4";

        private string CurrentPageUrl = "/Inventory/ItemMasterData.aspx";
        private string HeaderKeyName = "ItemCode";

        public static string KeepColumsContent = "";

        #region "Event"
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ClearScreen();

                MasterData masterDataWS = new MasterData();
                DataSet dsMaster;
                //-----------------------Shipping Type-----------------
                dsMaster = masterDataWS.GetShippingType(User.Identity.Name);
                if (dsMaster != null)
                {
                    dsMaster.Tables[0].Rows.Add("-1", "");
                    ddlShipping.DataSource = dsMaster.Tables[0];
                    ddlShipping.DataTextField = "TrnspName";
                    ddlShipping.DataValueField = "TrnspCode";
                    ddlShipping.DataBind();
                    ddlShipping.SelectedValue = "-1";
                }
                //-----------------------Serial--------------------
                dsMaster = masterDataWS.GetSeries(User.Identity.Name,DocType,"");
                if (dsMaster.Tables.Count > 0)
                {
                    ddlSeries.DataSource = dsMaster.Tables[0];
                    ddlSeries.DataTextField = "SeriesName";
                    ddlSeries.DataValueField = "Series";
                    ddlSeries.DataBind();
                }
                //-----------------------Manufacture--------------------
                dsMaster = masterDataWS.GetManufacture(User.Identity.Name);
                if (dsMaster.Tables.Count > 0)
                {
                    ddlManufacture.DataSource = dsMaster.Tables[0];
                    ddlManufacture.DataTextField = "FirmName";
                    ddlManufacture.DataValueField = "FirmCode";
                    ddlManufacture.DataBind();
                }
                //-----------------------Price List------------------
                dsMaster = masterDataWS.GetPriceList(User.Identity.Name);
                if (dsMaster.Tables.Count > 0)
                {
                    ddlPriceList.DataSource = dsMaster.Tables[0];
                    ddlPriceList.DataTextField = "ListName";
                    ddlPriceList.DataValueField = "ListNum";
                    ddlPriceList.DataBind();
                    
                }
                //-----------------------Item Group------------------
                dsMaster = masterDataWS.GetItemGroup(User.Identity.Name);
                if (dsMaster.Tables.Count > 0)
                {
                    ddlItemGroup.DataSource = dsMaster.Tables[0];
                    ddlItemGroup.DataTextField = "ItmsGrpNam";
                    ddlItemGroup.DataValueField = "ItmsGrpCod";
                    ddlItemGroup.DataBind();
                }

                //-----------------------Tax IN Group------------------
                dsMaster = masterDataWS.GetTaxGroup("I",User.Identity.Name);
                if (dsMaster.Tables.Count > 0)
                {
                    ddlPurTaxGroup.DataSource = dsMaster.Tables[0];
                    ddlPurTaxGroup.DataTextField = "Name";
                    ddlPurTaxGroup.DataValueField = "Code";
                    ddlPurTaxGroup.DataBind();
                }

                //-----------------------Tax OUT Group------------------
                dsMaster = masterDataWS.GetTaxGroup("O", User.Identity.Name);
                if (dsMaster.Tables.Count > 0)
                {
                    ddlSalTaxGroup.DataSource = dsMaster.Tables[0];
                    ddlSalTaxGroup.DataTextField = "Name";
                    ddlSalTaxGroup.DataValueField = "Code";
                    ddlSalTaxGroup.DataBind();
                }

                //-----------------------Tax Customs Group------------------
                dsMaster = masterDataWS.GetCustomGroup( User.Identity.Name);
                if (dsMaster.Tables.Count > 0)
                {
                    ddlPurCustomGroup.DataSource = dsMaster.Tables[0];
                    ddlPurCustomGroup.DataTextField = "CstGrpName";
                    ddlPurCustomGroup.DataValueField = "CstGrpCode";
                    ddlPurCustomGroup.DataBind();
                }

                //-----------------------Tax Order Interval------------------
                dsMaster = masterDataWS.GetOrderInterval( User.Identity.Name);
                if (dsMaster.Tables.Count > 0)
                {
                    ddlOrderInterval.DataSource = dsMaster.Tables[0];
                    ddlOrderInterval.DataTextField = "Name";
                    ddlOrderInterval.DataValueField = "Code";
                    ddlOrderInterval.DataBind();
                }
                string cardcode = Request.QueryString["itemcode"];
                if (!String.IsNullOrEmpty(cardcode))
                {
                    LoadData(cardcode);
                }
                else
                {
                    LoadDefault();
                }
            }
        }
        protected void btnAdd_Click(object sender, ImageClickEventArgs e)
        {
            if (txtItemCode.Text == "")
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                    "Main.setMasterMessage('Missing Item Code','');", true);
            }

            String requestXML = _collectData();
            SAP.WebServices.Transaction ts = new WebServices.Transaction();
            DataSet ds = ts.CreateMarketingDocument(requestXML, User.Identity.Name, DocType, "", false);
            if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
            {
                Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                Session["requestXML"] = requestXML;
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                    "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
            }
            else
            {
                Session["successMessage"] = "Operation complete sucessful!";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                   "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);

                ClearScreen();
            }
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                              "Dialog.hideLoader();", true);
        }
       
        protected void ddlSeries_SelectedIndexChanged(object sender, EventArgs e)
        {
            GenerateSeri();
        }
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                       case "EditProjectCallBack":
                            Project prj = Session["chosenProject"] as Project;
                            if (prj != null)
                            {
                                //this.txtProject.Text = prj.PrjCode;
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + ex.ToString() + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
        }      
        #endregion

        #region "Functions"
        private void LoadData(string ItemCode)
        {
            try
            {
                Transaction trx = new Transaction();
                dtHeader = trx.GetMarketingDocument_ReturnDS(DocType, ItemCode, User.Identity.Name).Tables[0];
                if (dtHeader.Rows.Count == 0)
                    ItemCode = "";
                DataSet ds = trx.GetMarketingDocument_ReturnDS(DocType, ItemCode, User.Identity.Name);
                dtHeader =GF.ConvertDataTable_RemoveCols(ds.Tables[0],"");

                DataRow dr = dtHeader.Rows[0];
               

                //-----------------header----------------
                ddlSeries.SelectedValue = dr["Series"].ToString();
                txtItemCode.Text = dr["ItemCode"].ToString();
                txtBarcode.Text = dr["CodeBars"].ToString();
                txtItemName.Text = dr["ItemName"].ToString();
                txtFName.Text=dr["FrgnName"].ToString();
                ddlItemType.SelectedValue = dr["ItemType"].ToString();
                ddlItemGroup.SelectedValue = dr["ItmsGrpCod"].ToString();
                if (dr["PrchseItem"].ToString() == "Y")
                    ckPurchaseItem.Checked = true;
                else
                    ckPurchaseItem.Checked = false;

                if (dr["SellItem"].ToString() == "Y")
                    ckSalesItem.Checked = true;
                else
                    ckSalesItem.Checked=false;

                if (dr["InvntItem"].ToString() == "Y")
                    ckInvItem.Checked = true;
                else
                    ckInvItem.Checked = false;
                //-----------general------------
                ddlManufacture.SelectedValue = dr["FirmCode"].ToString();
                txtAddID.Text = dr["SWW"].ToString();
                ddlShipping.SelectedValue = dr["ShipType"].ToString();
                //ddlIssueType.SelectedValue = dr["IssueMthd"].ToString();
                ////ddlManageBy.SelectedValue =dr["ItmsGrpCod"].ToString();
            
                //if (dr["Phantom"].ToString() == "Y")
                //    ckPhantom.Checked = true;
                //else
                //    ckPhantom.Checked = false;

                //----------purchasing----------
                txtPurRefVendor.Text = dr["CardCode"].ToString();
                txtPurMrfNo.Text = dr["SuppCatNum"].ToString();
                txtPurUOM.Text = dr["BuyUnitMsr"].ToString();
                txtPurchaseItemPer.Text = GF.FormatNumeric(dr["NumInBuy"].ToString(), "QtyDec");
                txtPurPackingUOM.Text = dr["PurPackMsr"].ToString();
                txtPurQtyPerPacking.Text = GF.FormatNumeric(dr["PurPackUn"].ToString(), "QtyDec"); 
                ddlPurCustomGroup.SelectedValue = dr["CstGrpCode"].ToString();
                ddlPurTaxGroup.SelectedValue=dr["VatGroupPu"].ToString();

                //txtPurLen.Text = GF.FormatNumeric(dr["BLen1Unit"].ToString(), "QtyDec");
                //txtPurWid.Text = GF.FormatNumeric(dr["BWidth1"].ToString(), "QtyDec");
                //txtPurHei.Text = GF.FormatNumeric(dr["BHeight1"].ToString(), "QtyDec"); 
                //txtPurWei.Text = GF.FormatNumeric(dr["BWeight1"].ToString(), "QtyDec"); 
                //txtPurVol.Text = GF.FormatNumeric(dr["BVolume"].ToString(), "QtyDec"); 
                //ddlPurVolUnit.SelectedValue = dr["BVolUnit"].ToString();
                //txtPurFac1.Text = GF.FormatNumeric(dr["PurFactor1"].ToString(), "QtyDec");
                //txtPurFac2.Text = GF.FormatNumeric(dr["PurFactor2"].ToString(), "QtyDec"); 
                //txtPurFac3.Text = GF.FormatNumeric(dr["PurFactor3"].ToString(), "QtyDec");
                //txtPurFac4.Text = GF.FormatNumeric(dr["PurFactor4"].ToString(), "QtyDec"); 

                //----------sales---------------
                txtSalUOM.Text = dr["SalUnitMsr"].ToString();
                txtSalItemPer.Text = GF.FormatNumeric(dr["NumInSale"].ToString(), "QtyDec");
                txtSalPackingUOM.Text = dr["SalPackMsr"].ToString();
                txtSalQtyPerPacking.Text = GF.FormatNumeric(dr["SalPackUn"].ToString(), "QtyDec"); 
                ddlSalTaxGroup.SelectedValue = dr["VatGourpSa"].ToString();

                //txtSalLen.Text = GF.FormatNumeric(dr["SLen1Unit"].ToString(), "QtyDec"); 
                //txtSalWid.Text = GF.FormatNumeric(dr["SWidth1"].ToString(), "QtyDec"); 
                //txtSalHei.Text = GF.FormatNumeric(dr["SHeight1"].ToString(), "QtyDec");
                //txtSalWei.Text = GF.FormatNumeric(dr["SWeight1"].ToString(), "QtyDec"); 
                //txtSalVol.Text = GF.FormatNumeric(dr["SVolume"].ToString(), "QtyDec"); 
                //ddlSalVolUnit.SelectedValue = dr["SVolUnit"].ToString();
                //txtSalFac1.Text = GF.FormatNumeric(dr["SalFactor1"].ToString(), "QtyDec"); 
                //txtSalFac2.Text = GF.FormatNumeric(dr["SalFactor2"].ToString(), "QtyDec");
                //txtSalFac3.Text = GF.FormatNumeric(dr["SalFactor3"].ToString(), "QtyDec"); 
                //txtSalFac4.Text = GF.FormatNumeric(dr["SalFactor4"].ToString(), "QtyDec");
                //-----------inventory----------
                ddlGLBy.SelectedValue = dr["GLMethod"].ToString();
                txtInvUOM.Text = dr["InvntryUom"].ToString();
                ddlValuationMethod.SelectedValue = dr["EvalSystem"].ToString();
                txtItemCost.Text = GF.FormatNumeric(dr["AvgPrice"].ToString(), "SumDec");
                txtMinInv.Text = GF.FormatNumeric(dr["MinLevel"].ToString(), "QtyDec"); 
                txtMaxIn.Text = GF.FormatNumeric(dr["MaxLevel"].ToString(), "QtyDec"); 
                txtRequireUOM.Text = dr["ReorderQty"].ToString();
                //-----------planning-----------
                ddlPlaningMethod.SelectedValue = dr["PlaningSys"].ToString();
                ddlProcurementMethod.SelectedValue = dr["PrcrmntMtd"].ToString();
                ddlOrderInterval.SelectedValue = dr["OrdrIntrvl"].ToString();
                txtOrderMultiple.Text = GF.FormatNumeric(dr["OrdrMulti"].ToString(), "QtyDec"); 
                txtMinOrder.Text = GF.FormatNumeric(dr["MinOrdrQty"].ToString(), "QtyDec"); 
                txtLeadTime.Text = dr["LeadTime"].ToString();
                txtTolerance.Text = dr["ToleranDay"].ToString();


                txtRemark.Text = dr["UserText"].ToString();

                MasterData md = new MasterData();
                DataTable dt = md.GetItemPrice(int.Parse(ddlPriceList.SelectedValue), txtItemCode.Text, User.Identity.Name).Tables[0];
                txtUnitPrice.Text = GF.FormatNumeric(dt.Rows[0]["Price"].ToString(), "PriceDec"); 

                SetNavigatorURL(txtItemCode.Text);

                HardCodeBachNumber();

                SetScreenStatus("Update");
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                    "Main.setMasterMessage('" +GeneralFunctions.UrlFullEncode( ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
        }
        public String _collectData()
        {
            try
            {
                DataRow dr = dtHeader.Rows[0];

                CultureInfo ivC = new System.Globalization.CultureInfo("es-US");

                dr["CardFName"] = txtFName.Text;
                dr["Free_Text"] = txtRemark.Text;
                if(ddlShipping.SelectedItem!=null)
                    dr["ShipType"] = ddlShipping.SelectedItem.Value.ToString();

                dr["Series"] = ddlSeries.SelectedItem.Value;
                dr["U_UserID"] = User.Identity.Name;
                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");
                dtHeader.TableName = TblHeaderName;
                ds.Tables.Add(dtHeader.Copy());

                return objInfo.ToXMLStringFromDS(DocType, ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + ex.ToString() + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
                return "";
            }
        }
        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnAdd.Visible = true;
                    btnUpdate.Visible = false;
                    break;
                case "Update":
                    btnAdd.Visible = false;
                    btnUpdate.Visible = false;
                    txtItemCode.Enabled = false;
                    break;
                case "Close":
                    btnAdd.Visible = false;
                    btnUpdate.Visible = false;
                    txtItemCode.Enabled = false;
                    break;
            }
        }
        private void ClearScreen()
        {
            //------------------create header table-----------------------------
            dtHeader = new DataTable("OITM");
            dtHeader.Columns.Add("ItemCode");
            dtHeader.Rows.Add();

            //--------------clear text-------------------
            txtFName.Text = "";
            txtRemark.Text = "";

            SetNavigatorURL("");
            SetScreenStatus("New");
        }
        protected void SetNavigatorURL(string CurrentKey)
        {
            GetDefault df = new GetDefault();
            DataSet nav = df.GetNextPreviousID(DocType, User.Identity.Name, TblHeaderName, HeaderKeyName, CurrentKey);
            if (nav != null)
            {
                this.linkFirst.NavigateUrl = CurrentPageUrl + "?itemcode=" + nav.Tables[0].Rows[0]["Fir"].ToString(); ;
                this.linkNext.NavigateUrl = CurrentPageUrl + "?itemcode=" + nav.Tables[0].Rows[0]["Nex"].ToString(); ;
                this.linkPrevious.NavigateUrl = CurrentPageUrl + "?itemcode=" + nav.Tables[0].Rows[0]["Pre"].ToString(); ;
                this.linkLast.NavigateUrl = CurrentPageUrl + "?itemcode=" + nav.Tables[0].Rows[0]["Las"].ToString(); ;
            }
            this.linkNew.NavigateUrl = CurrentPageUrl + "?itemcode=";
        }
        protected void LoadDefault()
        {
            if (ddlSeries.Items.FindByText("CRM") != null)
            {
                ddlSeries.Items.FindByText("CRM").Selected = true;
                GenerateSeri();
            }
            
        }
        protected void GenerateSeri()
        {
            MasterData masterDataWS = new MasterData();
            DataSet dsMaster;
            dsMaster = masterDataWS.GetSeries(User.Identity.Name, "2", "");
            DataView dv = new DataView(dsMaster.Tables[0]);
            dv.RowFilter = "Series=" + ddlSeries.SelectedValue;
            if (dv.Count > 0)
            {
                if (!string.IsNullOrEmpty(dv[0]["NextNumber"].ToString()))
                {
                    txtItemCode.Enabled = false;
                    string code = "";
                    code = dv[0]["BeginStr"].ToString();
                    for (int i = 0; i < (int)(dv[0]["NumSize"]) - dv[0]["NextNumber"].ToString().Length; i++)
                        code = code + "0";

                    code = code + dv[0]["NextNumber"].ToString();
                    txtItemCode.Text = code;
                }
                else
                {
                    txtItemCode.Enabled = true;
                    txtItemCode.Text = "";
                }
            }
            else
            {
                txtItemCode.Enabled = true;
                txtItemCode.Text = "";
            }
        }
        protected void HardCodeBachNumber()
        {
            DataTable dt;
            dt = new DataTable("OITM");
            dt.Columns.Add("No");
            dt.Columns.Add("DocDate");
            dt.Columns.Add("SlpName");
            dt.Columns.Add("WhsName");
            DataRow row ;
            
            row = dt.NewRow(); 
            row["No"]="1";
            row["DocDate"] = "JUO-01-999";
            row["SlpName"] = "31-Jun-2014";
            row["WhsName"] = "100";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["No"] = "2";
            row["DocDate"] = "JUO-02-888";
            row["SlpName"] = "15-Oct-2015";
            row["WhsName"] = "2000";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["No"] = "3";
            row["DocDate"] = "JUO-88-555";
            row["SlpName"] = "31-Dec-2015";
            row["WhsName"] = "100";
            dt.Rows.Add(row);

            lvHistory.DataSource = dt;
            lvHistory.DataBind();
        }
        #endregion

        protected void ddlPriceList_SelectedIndexChanged(object sender, EventArgs e)
        {
            MasterData md = new MasterData();
            DataTable dt = md.GetItemPrice(int.Parse(ddlPriceList.SelectedValue), txtItemCode.Text, User.Identity.Name).Tables[0];
            txtUnitPrice.Text = GF.FormatNumeric(dt.Rows[0]["Price"].ToString(), "PriceDec"); 
        }

      

    }
}